import {Button, Input, message, Upload, Radio, Tabs} from 'antd'
import React, {
	forwardRef,
	useEffect,
	useImperativeHandle,
	useState,
} from 'react'
import type {UploadFile} from 'antd/es/upload/interface'
import {useModel} from 'umi'
import type {RadioChangeEvent} from 'antd'
import styles from './index.less'
import {getPublicDownloadUrl, uploadFileUrl} from '@/service/common/upload'
import {
	getUserNameList,
	historicalFlowList,
	historyList,
} from '@/service/common'
import RecommendList from './RecommendList'

const {TextArea} = Input

type propsType = {
	moduleType?: string
	examineType: boolean
	orgId: number | string
	processInstanceId: string // 流程id
	activityId: string | undefined // 节点id
	recommendData: any[] // 推荐供应商列表
	required?: boolean
	passStatus: string
	bizNo: string
}

const examine = (props: propsType, ref: React.Ref<unknown> | undefined) => {
	const {
		examineType,
		orgId,
		activityId,
		processInstanceId,
		recommendData,
		required = false,
		passStatus,
		bizNo,
	} = props
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	// 审批备注
	const [notes, setNotes] = useState<string>('')
	const [fileList, setFileList] = useState<UploadFile[]>([])
	const [dataSourse, setDataSourse] = useState<any[]>([])
	const [datas, setDatas] = useState<any[]>([])
	const [userList, setUserList] = useState([])
	const [urlList, setUrlList] = useState([])
	const [refuseUrlList, setRefuseUrlList] = useState([])
	const [radioValue, setRadioValue] = useState<number>()
	const [supplierValue, setSupplierValue] = useState<number>()
	const [recommendList, setRecommendList] = useState<any[]>([]) // 采购供应商
	const [supplierName, setSupplierName] = useState<string>('')
	const [historyRejectData, setHistoryRejectData] = useState<any[]>([])
	const [activeKey, setActiveKey] = useState('审批意见')
	const [historyRejectDataNew, setHistoryRejectDataNew] = useState<any[]>([])
	useEffect(() => {
		if (
			activityId === 'recommendOther' ||
			activityId === 'recommendSourceType' ||
			activityId === 'countersign' ||
			activityId === 'superordinate'
		) {
			const newRecommendData = recommendData?.map((item) => ({
				...item,
				isSelected: '0',
			}))
			setRecommendList(newRecommendData)
		} else {
			setRecommendList(recommendData)
		}
	}, [activityId, recommendData])

	useEffect(() => {
		historyList({
			orgIds: orgId,
			id: processInstanceId,
			current: 1,
			size: 100,
		})
			.then((res: any) => {
				if (res?.success) {
					const newData: any[] = []
					const userIdArr: number[] = []
					let urlArr: string[] = []
					res?.data?.records?.forEach(
						(item: {
							activityName: string
							message: string
							url: string
							assignee: any
							nodeType: number
						}) => {
							if (
								item?.nodeType !== 2 &&
								item?.nodeType !== 4 &&
								item?.assignee
							) {
								newData.push(item)
								userIdArr.push(Number(item?.assignee))
								// const urls = item?.message ? JSON.parse(
								// 	item?.message,
								// )?.url?.split(',') : []
								let urls = []
								if (item?.nodeType === 3) {
									urls = JSON.parse(
										item?.message,
									)?.url?.split(',')
								} else {
									urls = item?.url?.split(',')
								}
								urlArr = urlArr.concat(urls)
							}
						},
					)
					if (userIdArr?.length) {
						getUserNameList({userIds: userIdArr}).then(
							(result: any) => {
								if (result?.success) {
									setUserList(result?.data)
								}
							},
						)
					}
					const urls = urlArr
						?.map(Number)
						?.filter((item: number) => item !== 0)
					if (urls?.length) {
						getPublicDownloadUrl(urls)
							.then((result: any) => {
								if (result?.success) {
									setUrlList(result?.data)
								}
							})
							.catch((err: any) => {
								message.error(err)
							})
					}

					setDataSourse(newData)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
			})
		historicalFlowList({
			bizType: 2,
			bizNo,
		}).then((res: any) => {
			if (res?.success) {
				let urlArr: string[] = []
				res?.data?.forEach((items: any) => {
					items?.forEach((item: any) => {
						if (
							item?.nodeType !== 2 &&
							item?.nodeType !== 4 &&
							item?.assignee
						) {
							let urls = []
							if (item?.nodeType === 3) {
								urls = JSON.parse(item?.message)?.url?.split(
									',',
								)
							} else {
								urls = item?.url?.split(',')
							}
							urlArr = urlArr.concat(urls)
						}
					})
				})
				const urls = urlArr
					?.map(Number)
					?.filter((item: number) => item !== 0)
				if (urls?.length) {
					getPublicDownloadUrl(urls)
						.then((result: any) => {
							if (result?.success) {
								setRefuseUrlList(result?.data)
							}
						})
						.catch((err: any) => {
							message.error(err)
						})
				}
				setHistoryRejectData(res?.data)
			}
		})
	}, [])
	useEffect(() => {
		if (userList?.length && dataSourse?.length) {
			const newData = [...dataSourse]
			dataSourse.forEach((item, index) => {
				if (item?.nodeType === 3) {
					newData.splice(index + 1, dataSourse?.length)
				}
			})
			const newDatas = [...newData]
			newData.forEach((item, index) => {
				newDatas[index].urlData = []
				const userData: any = userList?.find(
					(user: {id: number}) => user?.id === Number(item?.assignee),
				)
				urlList?.forEach((url: {id: number}) => {
					const urls =
						item?.nodeType === 3
							? JSON.parse(item?.message)?.url
							: item?.url
					if (urls?.includes(url?.id.toString())) {
						newDatas?.[index]?.urlData.push(url)
					}
				})
				if (userData) {
					newDatas[index].userName = userData?.name || ''
				}
			})
			setDatas(newDatas)
		}
	}, [dataSourse, userList, urlList])
	useEffect(() => {
		if (historyRejectData?.length) {
			const newData = [...historyRejectData]
			historyRejectData.forEach((items, indexs: number) => {
				items?.forEach((item: any, index: number) => {
					newData[indexs][index].urlData = []
					const userData: any = userList?.find(
						(user: {id: number}) =>
							user?.id === Number(item?.assignee),
					)
					refuseUrlList?.forEach((url: {id: number}) => {
						const urls =
							item?.nodeType === 3
								? JSON.parse(item?.message)?.url
								: item?.url
						if (urls?.includes(url?.id.toString())) {
							newData[indexs][index]?.urlData.push(url)
						}
					})
					if (userData) {
						newData[indexs][index].userName = userData?.name || ''
					}
				})
			})
			setHistoryRejectDataNew(newData)
		}
	}, [historyRejectData, refuseUrlList])
	useEffect(() => {
		if (dataSourse?.length) {
			setActiveKey('审批意见')
		} else if (dataSourse?.length === 0 && historyRejectData?.length) {
			setActiveKey('历史审批拒绝记录')
		}
	}, [dataSourse, historyRejectData])

	const uploadProps = {
		action: uploadFileUrl,
		name: fileName,
		data: {
			modelName: 'purchase',
			targetAttr: 0,
		},
		fileList,
		beforeUpload: (file: any) => {
			const defAccept = [
				'.pdf',
				'.docx',
				'.doc',
				'.doc',
				'.xlsx',
				'.xls',
				'.zip',
				'.jpeg',
				'.jpg',
				'.png',
				'.rar',
			]
			const gs = defAccept
			const lastName = file.name.substring(file.name.lastIndexOf('.'))
			if (!gs.includes(lastName)) {
				message.error('文件格式不正确')
			}
			const isLt200M = file.size / 1024 / 1024 < 200
			if (!isLt200M) {
				message.warning('文件必须小于200MB')
			}
			return isLt200M && lastName
		},
		onChange(info: any) {
			const defAccept = [
				'.pdf',
				'.docx',
				'.doc',
				'.doc',
				'.xlsx',
				'.xls',
				'.zip',
				'.jpeg',
				'.jpg',
				'.png',
				'.rar',
			]
			const gs = defAccept
			const lastName = info.file.name.substring(
				info.file.name.lastIndexOf('.'),
			)
			if (gs.includes(lastName)) {
				if (info.file.status) {
					setFileList(info.fileList)
				}
				if (info.file.status === 'done') {
					message.success(info?.file?.response.msg)
				} else if (info.file.status === 'error') {
					message.warning(info?.file?.response.msg)
				}
			}
		},
	}
	const onTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
		setNotes(e.target.value)
	}
	const onRadioChange = (e: RadioChangeEvent) => {
		setRadioValue(e.target.value)
	}
	const onSupplierChange = (e: RadioChangeEvent) => {
		const newData = [...recommendList]
		recommendList?.forEach((item, index) => {
			if (index + 1 === e.target.value) {
				newData[index].isSelected = '1'
				setSupplierName(item?.supplierName)
			} else {
				newData[index].isSelected = '0'
			}
		})
		setRecommendList(newData)
		setSupplierValue(e.target.value)
	}
	const onSubmit = () => {
		const examineUrl = fileList?.map(
			(item) => item?.response?.data?.id || item?.uid,
		)
		if (passStatus === '1') {
			if (activityId === 'recommendSourceType') {
				if (radioValue !== 0 && radioValue !== 1) {
					message.warning('请选择采购资源导入方式')
					return ''
				}
			}
			if (
				activityId === 'recommendOther' ||
				activityId === 'recommendSourceType' ||
				activityId === 'countersign' ||
				activityId === 'superordinate'
			) {
				const selectData = recommendList?.find(
					(item) => item?.isSelected === '1',
				)
				if (!selectData) {
					message.warning('请选择供应商')
					return ''
				}
			}

			const data: any = {
				message: notes,
				url: examineUrl?.toString(),
				supplierName,
			}
			if (radioValue === 0 || radioValue === 1) {
				data.sourceType = radioValue
			}
			if (recommendList?.length) {
				const newData = recommendList?.map((item) => {
					// eslint-disable-next-line @typescript-eslint/no-unused-vars
					const {key, ...info} = item
					return info
				})
				data.supplierList = newData
			}
			return data
		}
		return {
			message: notes,
			url: examineUrl?.toString(),
			supplierName,
		}
	}
	useImperativeHandle(ref, () => ({
		getData: onSubmit,
	}))

	const tabItem = []
	if (datas?.length) {
		tabItem.push({
			label: '审批意见',
			key: '审批意见',
			children: (
				<div className={styles.opinion}>
					<div>审批意见</div>
					{datas?.map((item) => {
						const messages = JSON.parse(item?.message)?.message
						const status = JSON.parse(item?.message)?.status
						const userName =
							item?.message.substr(0, 1) === '{' &&
							item?.message.substr(-1) === '}'
								? JSON.parse(item?.message)?.userName
								: ''
						return (
							<table border="1">
								<tr>
									<td>
										{userName ? '申请人' : item?.taskName}
									</td>
									<td>
										<div>
											<span className={styles.status}>
												{userName ? '作废' : status}
											</span>
											<span>
												{userName || item?.userName}
											</span>
											<span>{item?.endTime}</span>
										</div>
										{userName ? (
											''
										) : (
											<span
												className={styles.supplierName}>
												{item?.activityId ===
													'recommendOther' ||
												item?.activityId ===
													'recommendSourceType' ||
												item?.activityId ===
													'countersign' ||
												item?.activityId ===
													'superordinate' ? (
													<>
														{' '}
														选择供应商：
														{
															JSON.parse(
																item?.message,
															)?.supplierName
														}
													</>
												) : (
													''
												)}
											</span>
										)}
									</td>
								</tr>
								<tr>
									<td>附件</td>
									<td>
										{item?.urlData?.length ? (
											<>
												{item?.urlData?.map(
													(urlItem: {
														filename: string
														url: string | undefined
													}) => (
														<p>
															<span>
																{
																	urlItem?.filename
																}
															</span>
															<a
																href={
																	urlItem?.url
																}
																download={
																	urlItem?.filename
																}>
																下载
															</a>
														</p>
													),
												)}
											</>
										) : (
											<p>暂无附件</p>
										)}
									</td>
								</tr>
								<tr>
									<td>备注</td>
									<td>{messages || '暂无备注'}</td>
								</tr>
							</table>
						)
					})}
				</div>
			),
		})
	}
	if (historyRejectDataNew?.length) {
		tabItem.push({
			label: '历史审批拒绝记录',
			key: '历史审批拒绝记录',
			children: (
				<>
					{historyRejectDataNew?.map((items) => (
						<div className={styles.opinion}>
							<div>审批意见</div>
							{items?.map((item: any) => {
								if (item?.assignee === '') {
									return ''
								}
								const messages = JSON.parse(
									item?.message,
								)?.message
								const status = JSON.parse(item?.message)?.status
								const userName =
									item?.message.substr(0, 1) === '{' &&
									item?.message.substr(-1) === '}'
										? JSON.parse(item?.message)?.userName
										: ''
								return (
									<table border="1">
										<tr>
											<td>
												{userName
													? '申请人'
													: item?.taskName}
											</td>
											<td>
												<div>
													<span
														className={
															styles.status
														}>
														{userName
															? '作废'
															: status}
													</span>
													<span>
														{userName ||
															item?.assignee}
													</span>
													<span>{item?.endTime}</span>
												</div>
												{userName ? (
													''
												) : (
													<span
														className={
															styles.supplierName
														}>
														{item?.activityId ===
															'recommendOther' ||
														item?.activityId ===
															'recommendSourceType' ||
														item?.activityId ===
															'countersign' ||
														item?.activityId ===
															'superordinate' ? (
															<>
																{' '}
																选择供应商：
																{
																	JSON.parse(
																		item?.message,
																	)
																		?.supplierName
																}
															</>
														) : (
															''
														)}
													</span>
												)}
											</td>
										</tr>
										<tr>
											<td>附件</td>
											<td>
												{item?.urlData?.length ? (
													<>
														{item?.urlData?.map(
															(urlItem: {
																filename: string
																url:
																	| string
																	| undefined
															}) => (
																<p>
																	<span>
																		{
																			urlItem?.filename
																		}
																	</span>
																	<a
																		href={
																			urlItem?.url
																		}
																		download={
																			urlItem?.filename
																		}>
																		下载
																	</a>
																</p>
															),
														)}
													</>
												) : (
													<p>暂无附件</p>
												)}
											</td>
										</tr>
										<tr>
											<td>备注</td>
											<td>{messages || '暂无备注'}</td>
										</tr>
									</table>
								)
							})}
						</div>
					))}
				</>
			),
		})
	}

	return (
		<div className={styles.examine}>
			{examineType ? (
				<div className={styles.notes}>
					{activityId === 'recommendSourceType' ? (
						<p>
							<div>采购资源导入方式：</div>
							<Radio.Group
								onChange={onRadioChange}
								value={radioValue}>
								<Radio value={1}>比价会签</Radio>
								<Radio value={0}>例外采购</Radio>
							</Radio.Group>
						</p>
					) : (
						''
					)}
					{activityId === 'recommendOther' ||
					activityId === 'recommendSourceType' ? (
						<>
							<p> 采购供应商明细</p>
							<RecommendList
								type="process"
								recommendData={recommendList}
								setRecommendData={setRecommendList}
								select={false}
								recommendStatus={1}
								setSupplierValue={setSupplierValue}
								processType
							/>
						</>
					) : (
						''
					)}
					{activityId === 'recommendOther' ||
					activityId === 'recommendSourceType' ||
					activityId === 'countersign' ||
					activityId === 'superordinate' ? (
						<p>
							<div>选择供应商：</div>
							<Radio.Group
								onChange={onSupplierChange}
								value={supplierValue}>
								{recommendList?.map((item, index) => (
									<Radio value={index + 1}>
										{item?.supplierName}
									</Radio>
								))}
							</Radio.Group>
						</p>
					) : (
						''
					)}
					<p>
						<div>审批意见：</div>
						<TextArea
							style={{maxWidth: '700px'}}
							value={notes}
							maxLength={50}
							placeholder="请输入（最多50个字）"
							onChange={onTextChange}
							autoSize={{minRows: 3, maxRows: 3}}
						/>
					</p>
					<p>
						<div className={required ? styles.enclosure : ''}>
							添加附件：
						</div>
						<div>
							<Upload {...uploadProps}>
								{fileList?.length < 3 ? (
									<Button type="link" className={styles.btn}>
										请选择文件
									</Button>
								) : (
									''
								)}
							</Upload>
							<div className={styles.uploadTips}>
								附件说明：附件最大支持200M，支持格式：PDF、Word、Excel、JPG、PNG、ZIP、RAR
							</div>
						</div>
					</p>
				</div>
			) : (
				''
			)}
			{datas?.length || historyRejectData?.length ? (
				<Tabs
					type="card"
					onChange={(key) => {
						setActiveKey(key)
					}}
					activeKey={activeKey}
					items={tabItem}
				/>
			) : (
				''
			)}
		</div>
	)
}

export default forwardRef(examine)
